package com.zhiche.lisa.bms.controller.activiti;

import com.baomidou.mybatisplus.plugins.Page;
import com.zhiche.lisa.bms.dao.model.pay.PayApply;
import com.zhiche.lisa.bms.dao.model.quote.Quote;
import com.zhiche.lisa.bms.enums.ActivitiEnum;
import com.zhiche.lisa.bms.pojo.vo.activiti.HistoryTask;
import com.zhiche.lisa.bms.service.pay.PayApplyService;
import com.zhiche.lisa.bms.service.quote.QuoteService;
import com.zhiche.lisa.core.enums.CommonEnum;
import com.zhiche.lisa.core.supports.BaseException;
import com.zhiche.lisa.core.supports.RestfulResponse;
import com.zhiche.lisa.core.utils.Account.AccountUtil;
import com.zhiche.lisa.core.utils.Account.JwtAccountVO;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author linbao
 * @date 2018-10-16
 */
@RestController
@RequestMapping("/activitiCon")
@Slf4j
public class ActivitiController {

    @Autowired
    private QuoteService quoteService;

    @Autowired
    private PayApplyService payApplyService;

    /**
     * 报价单分页查询接口
     *
     * @param page
     * @return
     */
    @PostMapping(value = "/queryWaitConfirmPage")
    @ApiOperation(value = "根据条件查询待审批信息报价信息", notes = "根据条件查询待审批信息报价信息", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiResponses({@ApiResponse(code = 0, message = "success", response = Quote.class), @ApiResponse(code = -1, message = "系统异常")})
    public RestfulResponse<Page<Quote>> queryWaitConfirmPage(@RequestBody Page<Quote> page) {
        log.info("ActivitiController.queryWaitConfirmPage Param {} ", page);
        RestfulResponse<Page<Quote>> restful = new RestfulResponse<>(CommonEnum.SUCCESS.getCode(), CommonEnum.SUCCESS.getText(), null);
        try {
            setCurrentUserInfo(page);
            Page<Quote> quotePage = quoteService.queryWaitConfirmPage(page);
            restful.setData(quotePage);
        } catch (BaseException e) {
            log.error("ActivitiController.queryWaitConfirmPage baseException: {}", e.getMessage());
            setCommonErrorResult(restful, e.getMessage());
        } catch (Exception e) {
            log.error("ActivitiController.queryWaitConfirmPage error: {}", e.getMessage());
            setCommonErrorResult(restful, CommonEnum.ERROR.getText());
        }
        return restful;
    }

    /**
     * 报价单审核确认
     *
     * @param quote
     * @return
     */
    @PostMapping(value = "/computeQuoteTask")
    @ApiOperation(value = "报价单审核确认", notes = "报价单审核确认", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiResponses({@ApiResponse(code = 0, message = "success", response = RestfulResponse.class), @ApiResponse(code = -1, message = "系统异常")})
    public RestfulResponse<Object> computeQuoteTask(@RequestBody Quote quote) {
        log.info("ActivitiController.computeQuoteTask quote {} ", quote);
        RestfulResponse<Object> restful = new RestfulResponse<>(CommonEnum.SUCCESS.getCode(), CommonEnum.SUCCESS.getText(), null);
        try {
            quoteService.computeQuoteTask(quote.getId());
        } catch (BaseException e) {
            log.error("ActivitiController.computeQuoteTask baseException: {}", e.getMessage());
            setCommonErrorResult(restful, e.getMessage());
        } catch (Exception e) {
            log.error("ActivitiController.computeQuoteTask error: {}", e.getMessage());
            setCommonErrorResult(restful, CommonEnum.ERROR.getText());
        }
        return restful;
    }

    /**
     * 报价单审核不通过
     *
     * @param quote
     * @return
     */
    @PostMapping(value = "/auditFailQuote")
    @ApiOperation(value = "报价单审核不通过", notes = "报价单审核不通过", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiResponses({@ApiResponse(code = 0, message = "success", response = RestfulResponse.class), @ApiResponse(code = -1, message = "系统异常")})
    public RestfulResponse<Object> auditFailQuote(@RequestBody Quote quote) {
        log.info("ActivitiController.computeQuoteTask quote {} ", quote);
        RestfulResponse<Object> restful = new RestfulResponse<>(CommonEnum.SUCCESS.getCode(), CommonEnum.SUCCESS.getText(), null);
        try {
            quoteService.auditFailQuote(quote);
        } catch (BaseException e) {
            log.error("ActivitiController.auditFailQuote baseException: {}", e.getMessage());
            setCommonErrorResult(restful, e.getMessage());
        } catch (Exception e) {
            log.error("ActivitiController.auditFailQuote error: {}", e.getMessage());
            setCommonErrorResult(restful, CommonEnum.ERROR.getText());
        }
        return restful;
    }

    /**
     * 报价单获取审批历史
     *
     * @param quoteId
     * @return
     */
    @GetMapping(value = "/queryHistoryTaskList/{quoteId}")
    @ApiOperation(value = "获取审批历史", notes = "获取审批历史", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiResponses({@ApiResponse(code = 0, message = "success", response = RestfulResponse.class), @ApiResponse(code = -1, message = "系统异常")})
    public RestfulResponse<List<HistoryTask>> queryHistoryTaskList(@PathVariable Long quoteId) {
        log.info("ActivitiController.queryHistoryTaskList quote {} ", quoteId);
        RestfulResponse<List<HistoryTask>> restful = new RestfulResponse<>(CommonEnum.SUCCESS.getCode(), CommonEnum.SUCCESS.getText(), null);
        try {
            restful.setData(quoteService.queryHistoryTaskList(quoteId));
        } catch (BaseException e) {
            log.error("ActivitiController.queryHistoryTaskList baseException: {}", e.getMessage());
            setCommonErrorResult(restful, e.getMessage());
        } catch (Exception e) {
            log.error("ActivitiController.queryHistoryTaskList error: {}", e.getMessage());
            setCommonErrorResult(restful, CommonEnum.ERROR.getText());
        }
        return restful;
    }


    /**
     * 报价单分页查询接口
     *
     * @param page
     * @return
     */
    @PostMapping(value = "/queryWaitConfirmPayApplyPage")
    @ApiOperation(value = "查询支付申请待审核列表", notes = "查询支付申请待审核列表", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiResponses({@ApiResponse(code = 0, message = "success", response = Quote.class), @ApiResponse(code = -1, message = "系统异常")})
    public RestfulResponse<Page<PayApply>> queryWaitConfirmPayApplyPage(@RequestBody Page<PayApply> page) {
        log.info("ActivitiController.queryWaitConfirmPayApplyPage Param {} ", page);
        RestfulResponse<Page<PayApply>> restful = new RestfulResponse<>(CommonEnum.SUCCESS.getCode(), CommonEnum.SUCCESS.getText(), null);
        try {
            setCurrentUserInfo(page);
            Page<PayApply> resultData = payApplyService.queryWaitConfirmPayApplyPage(page);
            restful.setData(resultData);
        } catch (BaseException e) {
            log.error("ActivitiController.queryWaitConfirmPayApplyPage baseException: {}", e.getMessage());
            setCommonErrorResult(restful, e.getMessage());
        } catch (Exception e) {
            log.error("ActivitiController.queryWaitConfirmPayApplyPage error: {}", e.getMessage());
            setCommonErrorResult(restful, CommonEnum.ERROR.getText());
        }
        return restful;
    }

    /**
     * 支付申请单审核确认
     *
     * @param payApply
     * @return
     */
    @PostMapping(value = "/computePayApplyTask")
    @ApiOperation(value = "支付申请审核确认", notes = "支付申请审核确认", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiResponses({@ApiResponse(code = 0, message = "success", response = RestfulResponse.class), @ApiResponse(code = -1, message = "系统异常")})
    public RestfulResponse<Object> computePayApplyTask(@RequestBody PayApply payApply) {
        log.info("ActivitiController.computePayApplyTask payApply {} ", payApply);
        RestfulResponse<Object> restful = new RestfulResponse<>(CommonEnum.SUCCESS.getCode(), CommonEnum.SUCCESS.getText(), null);
        try {
            payApplyService.computePayApplyTask(payApply.getId());
        } catch (BaseException e) {
            log.error("ActivitiController.computePayApplyTask baseException: {}", e.getMessage());
            setCommonErrorResult(restful, e.getMessage());
        } catch (Exception e) {
            log.error("ActivitiController.computePayApplyTask error: {}", e.getMessage());
            setCommonErrorResult(restful, CommonEnum.ERROR.getText());
        }
        return restful;
    }

    /**
     * 支付申请单获取审批历史
     *
     * @param payApplyId
     * @return
     */
    @GetMapping(value = "/queryPayApplyHistoryTaskList/{payApplyId}")
    @ApiOperation(value = "获取审批历史", notes = "获取审批历史", httpMethod = "GET", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiResponses({@ApiResponse(code = 0, message = "success", response = RestfulResponse.class), @ApiResponse(code = -1, message = "系统异常")})
    public RestfulResponse<List<HistoryTask>> queryPayApplyHistoryTaskList(@PathVariable Long payApplyId) {
        log.info("ActivitiController.queryPayApplyHistoryTaskList payApplyId {} ", payApplyId);
        RestfulResponse<List<HistoryTask>> restful = new RestfulResponse<>(CommonEnum.SUCCESS.getCode(), CommonEnum.SUCCESS.getText(), null);
        try {
            restful.setData(payApplyService.queryPayApplyHistoryTaskList(payApplyId));
        } catch (BaseException e) {
            log.error("ActivitiController.queryPayApplyHistoryTaskList baseException: {}", e.getMessage());
            setCommonErrorResult(restful, e.getMessage());
        } catch (Exception e) {
            log.error("ActivitiController.queryPayApplyHistoryTaskList error: {}", e.getMessage());
            setCommonErrorResult(restful, CommonEnum.ERROR.getText());
        }
        return restful;
    }

    @GetMapping(value = "/getConfirmUser/{type}")
    @ApiOperation(value = "判断是否是报价单和支付申请单的审核人", notes = "判断是否是报价单和支付申请单的审核人", httpMethod = "GET", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiResponses({@ApiResponse(code = 0, message = "success", response = RestfulResponse.class), @ApiResponse(code = -1, message = "系统异常")})
    public RestfulResponse<Object> getConfirmUser(@PathVariable("type") String type) {
        log.info("ActivitiController.getConfirmUser");
        RestfulResponse<Object> restful = new RestfulResponse<>(CommonEnum.SUCCESS.getCode(), CommonEnum.SUCCESS.getText(), null);
        try {
            JwtAccountVO account = AccountUtil.getAccountInfoFromSecurityContext();
            if (account != null && StringUtils.isNotBlank(account.getUsername())) {
                if ("0".equals(type)) {
                    // 报价单
                    if (ActivitiEnum.quoteConfirmList.contains(account.getUsername())
                            || ActivitiEnum.conQuoteConfirmList.contains(account.getUsername())) {
                        restful.setData(1);
                    } else {
                        restful.setData(0);
                    }
                } else if ("1".equals(type)) {
                    // 支付申请单
                    if (ActivitiEnum.payApplyConfirmList.contains(account.getUsername())) {
                        restful.setData(1);
                    } else {
                        restful.setData(0);
                    }
                }
            }
        } catch (BaseException e) {
            log.error("ActivitiController.getConfirmUser baseException: {}", e.getMessage());
            setCommonErrorResult(restful, e.getMessage());
        } catch (Exception e) {
            log.error("ActivitiController.getConfirmUser error: {}", e.getMessage());
            setCommonErrorResult(restful, CommonEnum.ERROR.getText());
        }
        return restful;
    }

    /**
     * 设置统一异常信息
     *
     * @param result
     */
    private void setCommonErrorResult(RestfulResponse result, String errorMsg) {
        result.setCode(CommonEnum.ERROR.getCode());
        result.setMessage(errorMsg);
        result.setData(null);
    }

    /**
     * 设置当前登录用户信息
     *
     * @param page
     */
    private void setCurrentUserInfo(Page page) {
        JwtAccountVO account = AccountUtil.getAccountInfoFromSecurityContext();
        if (account != null) {
            page.getCondition().put(ActivitiEnum.CURRENT_USER_ID, account.getAccountId());
            page.getCondition().put(ActivitiEnum.CURRENT_USER_NAME, account.getUsername());
        }
    }
}
